package com.quanshu.exchange.ui.gui.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.quanshu.change.login.view.ResetPasswordByPhoneActivity;
import com.quanshu.change.tool.ReaseActivity;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.LoginInterface;
import com.quanshu.exchange.support.chat.ChatHelper;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.StateNationalEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.HomePageActivity;
import com.quanshu.exchange.ui.widget.LoadingDialog;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.base.view.BaseTitleBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.hyphenate.EMError.USER_ALREADY_LOGIN;

/**
 * 登录页面
 * Created by xiniu003 on 2017/11/28.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.phone_input)
    EditText phoneInput;
    @BindView(R.id.password_input)
    EditText passwordInput;
    @BindView(R.id.activity_national_flag)
    ImageView activityNationalFlag;
    @BindView(R.id.activity_state_name)
    TextView activityStateName;
    @BindView(R.id.state_national_flag)
    LinearLayout stateNationalFlag;
    @BindView(R.id.login_title)
    BaseTitleBar loginTitle;
    @BindView(R.id.login_title_txt)
    TextView loginTitleTxt;
    @BindView(R.id.login_phone)
    LinearLayout loginPhone;
    @BindView(R.id.login_pwd)
    LinearLayout loginPwd;
    @BindView(R.id.login_forget_pwd)
    FrameLayout loginForgetPwd;
    @BindView(R.id.login_to_register)
    FrameLayout loginToRegister;
    @BindView(R.id.login_submit)
    TextView loginSubmit;

    private String phoneInputStr;
    private String passwordInputStr;
    private String flag_id = "86";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ReaseActivity.assistActivity(this);
        ButterKnife.bind(this);
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    private void initListener() {
        ImmersionBar.with(this).statusBarColor("#FFFFFF").statusBarDarkFont(true).titleBar(loginTitle)
                .keyboardEnable(true)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)  //单独指定软键盘模式
                .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        Log.d("软键盘", "onKeyboardChange: " + isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                    }
                }).init();
        RxViewHelper.getInstance().clicks(stateNationalFlag, aVoid ->
                doShowFlag());
        loginTitle.setRightImage(R.drawable.icon_login_close_2_0).setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
            @Override
            public void onclickLeft() {
            }

            @Override
            public void onclickRight() {
                finish();
            }
        });
        RxViewHelper.getInstance().clicks(loginSubmit, aVoid -> doLogin());
        RxViewHelper.getInstance().clicks(loginToRegister, aVoid -> goRegister());
        RxViewHelper.getInstance().afterTextChangeEvents(phoneInput,
                textViewAfterTextChangeEvent -> {
                    phoneInputStr = textViewAfterTextChangeEvent.editable().toString();
                    setViewState();
                });
        RxViewHelper.getInstance().afterTextChangeEvents(passwordInput,
                textViewAfterTextChangeEvent -> {
                    passwordInputStr = textViewAfterTextChangeEvent.editable().toString();
                    setViewState();
                });

        RxViewHelper.getInstance().clicks(loginForgetPwd, aVoid -> goSetPwdActivity());
    }

    /**
     * 重置登录密码
     */
    private void goSetPwdActivity() {
        BaseTool.goActivity(this, ResetPasswordByPhoneActivity.class, null);

    }

    private void doShowFlag() {

        ArrayList<StateNationalEntity> list = AppUtils.stateData();

        DialogFlagList dialogFlagList = new DialogFlagList(this);
        dialogFlagList.show();
        dialogFlagList.setData(list);
        dialogFlagList.getItemClickSubject().subscribe(stateNationalEntity -> {
            dialogFlagList.dismiss();
            activityStateName.setText(stateNationalEntity.getFlag_name());
            activityNationalFlag.setImageResource(stateNationalEntity.getFlag_national());
            flag_id = String.valueOf(stateNationalEntity.getFlag_id());

        });
    }

    private void doLogin() {
        if (TextUtils.isEmpty(phoneInputStr)) {
            ToastHelper.toast("请输入手机号");
            return;
        }
        if (flag_id.equals("86")) {
            if (!CheckUtil.checkTelNumRule(phoneInputStr)) {
                ToastHelper.toast("手机号格式不正确");
                return;
            }
        }
        if (TextUtils.isEmpty(passwordInputStr)) {
            ToastHelper.toast("请输入密码");
            return;
        }
        String pinjiePhone = flag_id + phoneInputStr;
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .doLogin(AppUtils.getSignParams(pinjiePhone, passwordInputStr), pinjiePhone, passwordInputStr)
                .compose(new BaseTransformer<>(this, true, false))
                .subscribe(new BaseObserver<BaseResponse<UserEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserEntity> response) {

                        LoadingDialog loadingDialog = new LoadingDialog(LoginActivity.this, false);
                        loadingDialog.show();
                        MyApplication.getInstance().setCurrentUser(response.getData());
                        MyApplication.getInstance().getCurrentUser().setAvatar(Config.URL_HOST_SHOP_IMG+response.getData().getAvatar());
                        MyApplication.getInstance().setToken(response.getToken());

                        //登录环信
                        doLoginEase(response.getData(), loadingDialog);
                    }
                });
    }

    private void goRegister() {
        Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(intent);
    }

    private void setViewState() {
        if (!TextUtils.isEmpty(phoneInputStr) && !TextUtils.isEmpty(passwordInputStr)) {
            loginSubmit.setEnabled(true);
        } else {
            loginSubmit.setEnabled(false);
        }
    }

    private void doLoginEase(UserEntity entity, final LoadingDialog loadingDialog) {
        EMClient.getInstance().login(entity.getMemberid(), "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    Intent intent = new Intent(LoginActivity.this, HomePageActivity.class);
                    startActivity(intent);
                    finish();
                });
            }

            @Override
            public void onError(int code, String error) {
                runOnUiThread(() -> {
                    if (code == USER_ALREADY_LOGIN) {
                        ChatHelper.getInstance().logout(true, null);
                    }
                    loadingDialog.dismiss();
                    LogUtil.print("=====login==error===" + error);
                    ToastHelper.toast("登录失败,重新登录");
                });
            }

            @Override
            public void onProgress(int progress, String status) {
            }
        });
    }
}
